package com.tbit.uqbike.service.business.impl;

import cn.hutool.http.HttpUtil;
import com.tbit.uqbike.constant.OperaPswConstant;
import com.tbit.uqbike.constant.ServiceUrlConstant;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.Account;
import com.tbit.uqbike.object.pojo.HolderAccountBound;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.service.base.TokenService;
import com.tbit.uqbike.service.business.HolderAccountBoundService;
import com.tbit.uqbike.webmanager.dao.core.HolderAccountBoundDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author: chen
 * @Description: 股东区域绑定
 * @Date: 创建于 16:05 2020/8/13
 */
@Service
@Slf4j
public class HolderAccountBoundServiceImpl implements HolderAccountBoundService {
    @Autowired
    private HolderAccountBoundDao holderAccountBoundDao;
    @Autowired
    private TokenService tokenService;

    @Override
    public List<HolderAccountBound> getByAccountUserId(Integer accountUserId) {

        return holderAccountBoundDao.getByAccountUserId(accountUserId);
    }

    @Override
    public void insert(HolderAccountBound holderAccountBound) {
        HolderAccountBound holderAccountBoundDB = holderAccountBoundDao.getIsExist(holderAccountBound);
        if (holderAccountBoundDB != null) {
            throw new BaseException("ver.holder.is.exist");
        }
        holderAccountBound.setBoundTime(new Date());
        cleanToken(holderAccountBound);
        holderAccountBoundDao.insert(holderAccountBound);
    }

    private void cleanToken(HolderAccountBound holderAccountBound) {
        // clear token
        tokenService.destroyToken(new LoginInfo(holderAccountBound.getAccountUserId()));
        //修改运维端权限通知运维端删除角色token
        String url = OperaPswConstant.ACCOUNT_OPERA_MAIN_URL + ServiceUrlConstant.MAIN_UPDATE_NOTICE + "?accountUserId=" + holderAccountBound.getAccountUserId();
        String res = HttpUtil.get(url);
        log.info("调用url:{},运维端返回:{}", url, res);
    }

    @Override
    public void del(HolderAccountBound holderAccountBound) {
        holderAccountBoundDao.del(holderAccountBound);
        cleanToken(holderAccountBound);
    }

    @Override
    public List<Account> getAccountByUserId(Integer accountUserId) {
        return holderAccountBoundDao.selectAccount(accountUserId);
    }

    @Override
    public long getCountByUserId(Integer accountUserId) {
        return holderAccountBoundDao.selectCountByUserId(accountUserId);
    }
}
